package com.odin.core.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model){
        System.out.println("=======================login===============================");
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        //String exception = (String) request.getAttribute("shiroLoginFailure");
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        if( request.getParameter("userName")==null || "".equals(request.getParameter("userName"))){
            return "/login";
        }
        if( request.getParameter("password")==null || "".equals(request.getParameter("password"))){
            return "/login";
        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                request.getParameter("userName"),
                request.getParameter("password"));
        //进行验证，这里可以捕获异常，然后返回对应信息
        String msg = "";
        try{    subject.login(usernamePasswordToken);}
        catch (UnknownAccountException e){
            System.out.println("UnknownAccountException -- > 账号不存在：");
            msg = "UnknownAccountException -- > 账号不存在：";
            model.addAttribute("msg", msg);
            return "/login";
        }
        catch (IncorrectCredentialsException e){
            System.out.println("IncorrectCredentialsException -- > 密码不正确：");
            msg = "IncorrectCredentialsException -- > 密码不正确：";
            model.addAttribute("msg", msg);
            return "/login";
        }
        catch (Exception e){
            msg = "else >> "+e;
            System.out.println("else -- >" + e);
            model.addAttribute("msg", msg);
            return "/login";
        }
        model.addAttribute("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理
        return "index";
    }

 @RequestMapping("/index")
    public String toIndex(){
        return "index";
    }
      /*
    @RequestMapping("403")
    public String to403(){
        return "403";
    }

    //登出
    @RequestMapping(value = "logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    //错误页面展示
    @RequestMapping(value = "error",method = RequestMethod.POST)
    public String error(){
        return "error";
    }
  */


}
